var express = require('express');
var router = express.Router();
var sqlite3 = require('sqlite3').verbose();
var path = require('path');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
/* GET users listing. */
router.get('/', function(req, res, next) {
    var db=new sqlite3.Database(path.join(__dirname, "../db/LH.s3db"));
    if(req.query.upload=='1'){
        try{
            sqlStr1 = "SELECT * FROM s_activity WHERE s_id = ? and a_no = ?"
            sqlStr2 = "UPDATE s_activity SET material = ? and status = 1 where a_no = ? and s_id = ?"
            sqlStr3 = "INSERT INTO s_activity values(?,?,1,?,0,?,?)";
            sqlStr4 = "UPDATE activity SET s_num = s_num + 1 where a_no = ? "
            sqlStr5 = "UPDATE s_activity SET status = 1 WHERE s_id = ? and a_no = ?"
            db.all(sqlStr1, [req.session.username,req.query.a_no],function(err,rows){
                if(rows.length==0){//未加入
                    db.all(sqlStr3, [req.session.username,req.query.a_no,req.query.time,req.query.time.substring(0,4),''],function(err){
                        if(err!=null){
                            res.send('0');
                        }else{
                            db.all(sqlStr4, [req.query.a_no],function(err){//活动人数+1
                                if(err!=null){
                                    res.send('0');
                                }else{
                                    res.send('1');
                                }
                            } );
                        }
                    } );
                }else{//已加入
                    db.all(sqlStr2, ['',req.query.a_no,req.session.username],function(err){
                        if(err!=null){
                            res.send('0');
                        }else{//修改状态
                            db.all(sqlStr5, [req.session.username,req.query.a_no],function(err){//活动人数+1
                                if(err!=null){
                                    res.send('0');
                                }else{
                                    res.send('1');
                                }
                            } );
                        }
                    } );
                }
            } );
        }catch(ex){
            console.log(ex);
        }
    }
    else if(req.query.download=='1'){//下载
        try{
            sqlStr1 = "SELECT material FROM s_activity"
            db.all(sqlStr1,[],function(err,rows){
                if(rows.length==0){
                    res.send('0');
                }else{
                    res.send(rows[0].material);
                }
            } );
        }catch(ex){
            console.log(ex);
        }
    }

 });

module.exports = router;
